package com.ruoyi.websocket.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cfuser.api.rescue.RemoteInitiateService;
import com.ruoyi.cfuser.api.rescue.domain.RescueTask;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.shop.api.RemoteShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class SendMessageService {
    @Resource
    private WebSocketService webSocketService;
    @Resource
    private RemoteInitiateService remoteInitiateService;
    @Resource
    private RemoteShopService remoteShopService;
    @Autowired
    private RedisService redisService;

    public void sendMessage(RescueTask rescueTask){
        Map<String, Object> initMap = remoteInitiateService.filterId(rescueTask);
        List<String> list = (List) initMap.get("shopIds");
        List<String> shopIds = new ArrayList(); //  记录在范围内且有维修服务的商家id
        if (list != null && list.size() > 0) {
            // 循环符合范围的商家id,筛选出范围内有维修业务的商家id
            for (String id : list) {
                AjaxResult info = remoteShopService.getInfo(Long.parseLong(id));
                if ((Integer)info.get("code") == 200){
                    LinkedHashMap map = (LinkedHashMap)info.get("data");
                    List<String> serviceDetails = (List<String>) map.get("serviceDetails");
                    for (String serviceDetail : serviceDetails) {
                        System.out.println(serviceDetail);
                        if (serviceDetail.equals("维修")){
                            shopIds.add(id);
                        }
                    }
                }
            }
            //  把任务加入redis并向商家发送消息通知
            for (String shopId : shopIds) {
                System.out.println("shopid运行一次");
                List<String> taskList = redisService.getCacheList("taskList" + shopId);
                taskList.add(JSON.toJSONString(initMap.get("rescueTask")));
                redisService.deleteObject("taskList" + shopId);
                redisService.setCacheList("taskList" + shopId, taskList);
            System.out.println("resuceTask:" + JSON.toJSONString(initMap.get("rescueTask")));
                webSocketService.sendMessage(shopId,JSON.toJSONString(initMap.get("rescueTask")));
            }
            //  把任务消息发送到延迟队列
            String jsonString = JSON.toJSONString(initMap.get("rescueTask"));
            RescueTask rescueTask1 = JSONObject.parseObject(jsonString, RescueTask.class);
            String id = String.valueOf(rescueTask1.getId());
            remoteInitiateService.rabbit(id);
        }else {
            System.out.println("list is null！！！");
        }
    }
}
